package com.pms.utils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
/**
 * MD5生成器
 * @author huyinsong
 *
 */
public class MD5 {

	static MessageDigest md;
	static {
		try {
			md = MessageDigest.getInstance("MD5");
		} catch (Exception e) {
			md = null;
		}
	}

	/**
	 * 生成md5
	 * 
	 * @param source
	 * @return md5值
	 */
	public static String getMD5Code(String source) {
		if (md != null) {
			try {
				return byte2hexString(md.digest(source.getBytes("utf-8")));
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
		return source;
	}

	private static String byte2hexString(byte[] bytes) {
		StringBuffer buf = new StringBuffer(bytes.length * 2);
		for (int i = 0; i < bytes.length; i++) {
			if (((int) bytes[i] & 0xff) < 0x10) {
				buf.append("0");
			}
			buf.append(Long.toString((int) bytes[i] & 0xff, 16));
		}
		return buf.toString();
	}
}
